import React, { Component } from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'
import { Link } from 'react-router-dom'
import NavHeader from '@/components/NavHeader'
import styles from './index.module.css'
import { userRegistered } from '@/api/user'
import { withFormik } from 'formik'
import * as Yup from 'yup'

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{3,12}$/

class Registe extends Component {
  state = {
    username: '',
    password: '',
    password2: ''
  }

  handleSubmit = async e => {
    e.preventDefault()
  }
  getUserName = e => {
    this.setState({
      username: e.target.value
    })
  }
  getPassword = e => {
    this.setState({
      password: e.target.value
    })
  }
  getPassword2 = e => {
    this.setState({
      password2: e.target.value
    })
  }
  render () {
    const { values, handleSubmit, handleChange, handleBlur, errors, touched } =
      this.props
    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavHeader className={styles.navHeader}>注册</NavHeader>
        <WhiteSpace size='xl' />
        <WingBlank>
          <form onSubmit={handleSubmit}>
            <div className={styles.formItem}>
              <label className={styles.label}>用户名</label>
              <input
                name='username'
                value={values.username}
                onChange={handleChange}
                onBlur={handleBlur}
                className={styles.input}
                placeholder='请输入账号'
              />
            </div>
            {/* 长度为5到8位，只能出现数字、字母、下划线 */}
            {errors.username && touched.username && (
              <div className={styles.error}>{errors.username}</div>
            )}
            <div className={styles.formItem}>
              <label className={styles.label}>密码</label>
              <input
                className={styles.input}
                value={values.password}
                onChange={handleChange}
                onBlur={handleBlur}
                name='password'
                type='text'
                placeholder='请输入密码'
              />
            </div>
            {/* 长度为3到12位，只能出现数字、字母、下划线 */}
            {errors.password && touched.password && (
              <div className={styles.error}>{errors.password}</div>
            )}
            <div className={styles.formItem}>
              <label className={styles.label}>重复密码</label>
              <input
                className={styles.input}
                value={values.password2}
                onChange={handleChange}
                onBlur={handleBlur}
                name='password2'
                type='text'
                placeholder='请重新输入密码'
              />
            </div>
            {/* 确认密码为必填项，确认密码必须和密码一致 */}
            {errors.password2 && touched.password2 && (
              <div className={styles.error}>{errors.password2}</div>
            )}
            <div className={styles.formSubmit}>
              <button className={styles.submit} type='submit'>
                注册
              </button>
            </div>
          </form>
          <Flex className={styles.backHome} justify='between'>
            <Link to='/home'>点我回首页</Link>
            <Link to='/login'>已有账号，去登录</Link>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

export default withFormik({
  mapPropsToValues: () => ({ username: '', password: '', password2: '' }),
  handleSubmit: async (values, { props }) => {
    console.log(values)
    const { username, password } = values
    let param = {
      username,
      password
    }
    const { data: res } = await userRegistered(param)
    console.log('测试注册返回', res)
    const { status, body, description } = res
    if (status === 200) {
      // 登录成功
      localStorage.setItem('hkzf_token', body.token)
      props.history.push('/home')
    } else {
      // 登录失败
      Toast.info(description, 2, null, false)
    }
  },
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required('账号为必填项')
      .matches(REG_UNAME, '长度为5到8位，只能出现数字、字母、下划线'),
    password: Yup.string()
      .required('密码为必填项')
      .matches(REG_PWD, '长度为5到12位，只能出现数字、字母、下划线'),
    password2: Yup.string()
      .oneOf([Yup.ref('password'), null], '确认密码必须和密码一致')
      .required('确认密码为必填项')
  })
})(Registe)
